package com.web.quartz.job;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import com.web.common.basic.quartz.entity.QuartzCronTask;
import com.web.quartz.service.impl.QuartzOperateServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统固定的定时任务，项目启动时会自动添加的定时任务。
 * 
 * @author zhouhui
 * @since 1.0.0
 */
@Slf4j
@Component
public class FixedQuartzJobInit implements CommandLineRunner {
	
	public static final String FIXED_GROUP_NAME = "FIXED_GROUP";
	
	/** 每小时执行一次 */
	private static final String EVERY_HOUR = "0 0 0/1 * * ?";
	
	@Autowired
	private QuartzOperateServiceImpl quartzOperateServiceImpl;

	@Override
	public void run(String... args) throws Exception {
		log.info("---- 添加定时任务 start----");
		
		createCronJob("定时删除日志", LogHistoryDeleteJob.class, "0 0 1 * * ?");
		
		createCronJob("定时取消到期的分享文件", AutoCancelShareFileJob.class, EVERY_HOUR);
		
		createCronJob("定时取消到期的分享文档", AutoCancelShareDocJob.class, EVERY_HOUR);
		
		log.info("---- 添加定时任务 end ----");
	}

	/**
	 * 创建系统内置的cron定时任务
	 * @param jobName 定时任务名称
	 * @param cls 对应的类
	 * @param cron cron表达式
	 *
	 * @author zhouhui
	 * @since 1.0.0
	 */
	private void createCronJob(String jobName, Class<? extends QuartzJobBean> cls, String cron) {
		QuartzCronTask task = new QuartzCronTask();
		task.setJobName(jobName);
		task.setJobClass(cls);
		task.setCron(cron);
		task.setGroupName(FIXED_GROUP_NAME);
		quartzOperateServiceImpl.cronSimpleQuartz(task);
	}
}
